package uqueue

import (
	"time"
	"sync"
)

type TaskItem interface {
	Doing()
}

type SlowQueue struct {
	ListC 		chan TaskItem
	stop 		chan bool
	sleep 		time.Duration
}

func NewSlowQueue(bufLen int, sleep time.Duration) *SlowQueue {
	if bufLen == 0 {
		bufLen = 2048
	}
	if sleep > 1 * time.Second {
		sleep = 1 * time.Second
	}

	return &SlowQueue{
		ListC: make(chan TaskItem, bufLen),
		stop: make(chan bool),
		sleep: sleep,
	}
}

func (q *SlowQueue) Stop()  {
	q.stop <- false
	return
}

func (q *SlowQueue) Wait(wg *sync.WaitGroup)  {
	wg.Wait()
	return
}

func (q *SlowQueue) Run(wg *sync.WaitGroup)  {
	go q.run(wg)
}

func (q *SlowQueue) run(wg *sync.WaitGroup)  {
	wg.Add(1)
	for {
		select {
		case item := <- q.ListC:
			if q.sleep > 0 {
				time.Sleep(q.sleep)
			}
			item.Doing()
		case <- q.stop:
			wg.Done()
			return
		}
	}
}